package cn.fhj.sohu;

import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fhj.util.StringUtil;

public class MainFrm extends JFrame {
	private static final long serialVersionUID = 1983923261476635370L;
	private JTextField name = new JTextField("方舟子");// 山再那里0001 / 方舟子
	private JButton begin = new JButton("备份");
	private JButton searchBt = new JButton("搜索");
	private JFileChooser jfc = new JFileChooser();
	private JTextField saveDir = new JTextField("c:/sohu");
	private JButton dirBt = new JButton(":");
	private JProgressBar progress = new JProgressBar();
	private final static Log log = LogFactory.getLog(MainFrm.class);
	private JCheckBox includePic = new JCheckBox("包含图片");

	public MainFrm() {
		setResizable(false);
		log.info("启动...");
		setLayout(null);
		this.setTitle("备份Sohu微博");
		JLabel bokLbl = new JLabel();
		add(bokLbl);
		bokLbl.setText("输入微博名称：");
		int x = 30, y = 10, length = 120, height = 25;

		this.add(name);
		this.add(begin);
		this.add(searchBt);
		final JLabel saveDirLbl = new JLabel();
		add(saveDirLbl);
		saveDirLbl.setText("备份存储目录: ");
		saveDirLbl.setBounds(x, y, length, height);

		add(saveDir);
		saveDir.setBounds(x + length-20, y, 3 * length + 130, height);
		saveDir.setEditable(false);

		add(dirBt);
		dirBt.setBounds(x + 4 * length + 110, y, length / 3, height);

		y += height + 20;
		bokLbl.setBounds(x, y, length, height);
		name.setBounds(x + length-20, y, length + 100, height);

		add(includePic);
		includePic.setSelected(true);
		includePic.setBounds(x + 3 * length - 30, y, 90, height);

		begin.setBounds(x + 4 * length - 50, y, length - 30, height);
		searchBt.setBounds(x + 5 * length - 60, y, length - 30, height);
		progress.setStringPainted(true); // 设置进度条呈现进度字符串,默认为false

		add(progress);

		y += height + 20;
		progress.setBounds(20, y, 5 * length + 20, 2 * height);

		setSize(680, 200);
		setVisible(true);
		double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();

		double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();

		setLocation(new Point((int) (lx / 2) - this.getWidth() / 2, (int) (ly / 2) - this.getHeight() / 2));// 设定窗口出现位置
		begin.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainFrm.this.setButtons(false);
				if (StringUtil.isEmpty(name.getText())) {
					name.grabFocus();
					MainFrm.this.setButtons(true);
					return;
				}
				String dir = saveDir.getText();
				if (StringUtil.isEmpty(dir)) {
					dirBt.grabFocus();
					MainFrm.this.setButtons(true);
					return;
				}

				MainFrm.this.setButtons(false);
				String bokName = name.getText().trim();
				bakcup = new Backup(dir + '/' + bokName + '/', bokName, progress, includePic.isSelected());

				progress.setValue(0);
				progress.setString("0 % ");
				bakcup.excute();
			}

		});

		dirBt.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				String dir = getSaveDir();
				if (dir == null) {
					name.grabFocus();
					return;
				}
				saveDir.setText(dir);

			}

			private String getSaveDir() {
				jfc.setFileSelectionMode(1);// 设定只能选择到文件夹
				int state = jfc.showOpenDialog(MainFrm.this);// 此句是打开文件选择器界面的触发语句
				if (state == 1) {
					return null;
				} else {
					File f = jfc.getSelectedFile();// f为选择到的目录
					return f.getAbsolutePath();
				}
			}
		});
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent evt) {
				if (progress.getValue() == 0
						|| progress.getValue() == progress.getMaximum()
						|| JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null,
								"若不改变备份存储目录，下次备份时将自动继续本次的备份。确定退出？", "退出", JOptionPane.YES_NO_OPTION,
								JOptionPane.WARNING_MESSAGE)) {
					while (bakcup != null && !bakcup.canExit()) {
						progress.setString("系统退出中 ...");
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// Ignore
						}
					}
					log.warn("退出系统");
					System.exit(0);
				}
			}
		});

		searchBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				if (name.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null, "请输入已备份的微博用户名");
					name.grabFocus();
					return;
				}
				String bkName = name.getText().trim();
				File file = new File(saveDir.getText() + '/' + bkName);
				if (!file.exists()) {
					JOptionPane.showMessageDialog(null, saveDir.getText() + " 目录下未发现备份过 " + name.getText() + " 微博");
					name.grabFocus();
					return;
				}
				String keys = JOptionPane.showInputDialog("输入关键字，多个关键字空格分隔");
				if (StringUtil.isEmpty(keys)) {
					return;
				}
				MainFrm.this.setButtons(false);
				bakcup = new Backup(saveDir.getText() + '/' + bkName + '/', bkName, progress, includePic.isSelected());

				progress.setValue(0);
				progress.setString("0 % ");
				bakcup.search(keys);
			}

		});
	}

	private Backup bakcup;

	protected static MainFrm frm;

	public static void main(String[] args) {
		frm = new MainFrm();
	}

	private void setButtons(boolean enable) {
		begin.setEnabled(enable);
		dirBt.setEnabled(enable);
		searchBt.setEnabled(enable);
		name.setEditable(enable);
	}

	public static void finsihed() {
		frm.setButtons(true);
	}
}
